<template>
	<view>
		<view class="settle-box">
			<view class="settle-type-box">
				<view class="tabs">
					<view class="tab" :class="{ active: tabActive === 1 }" @click="changeTab(1)">快递邮寄
					</view>
					<view class="tab" :class="{ active1: tabActive === 2 }" @click="changeTab(2)">自提
					</view>
				</view>
				<view class="mail" v-if="tabActive === 1">
					<view v-if="addressInfo.id">
						<view class="address">
							{{
                addressInfo.provinceName +
                addressInfo.cityName +
                addressInfo.countyName
              }}
							<text class="isDefault" v-if="addressInfo.isDefault == 1">默认
							</text>
						</view>
						<view class="address-desc" @click="link('/page_my/address/list?form=settle')">
							<view class="address-txt">{{ addressInfo.address }}</view>
							<image class="go-change" :src="`${img_baseUrl}/statics/std/static/go_gray.png`">
							</image>
						</view>
						<view>
							<text class="name">{{ addressInfo.name }}</text>
							<text class="phone">{{ addressInfo.phone }}</text>
						</view>
					</view>
					<view v-else>
						<view class="no-address-box" @click="link('/page_my/address/list?form=settle')">
							<view class="left-box">
								<image class="add-icon"
									:src="`${img_baseUrl}/statics/std/static/new/add_gray.png`"></image>
								<text class="add-txt">添加地址</text>
							</view>
							<image class="go-change" :src="`${img_baseUrl}/statics/std/static/go_gray.png`">
							</image>
						</view>
					</view>
					<view class='bor_bot'></view>
				</view>
				<view v-else class="pick-up">
					<view class="address-desc">
						<view class="pick-up-text">自提点</view>
						<view class="flex-between-content"
							@click="addressDetail ? link(`/page_my/pickUpPoint/index?id=${list[0].storeId}`) : null">
							<view class="adress-text">
              {{ pickUpInfo.provinceName + pickUpInfo.cityName + pickUpInfo.countyName + pickUpInfo.address || '暂无自提点' }}
              </view>
							<image v-if="addressDetail" class="go-change" :src="`${img_baseUrl}/statics/std/static/go_gray.png`">
							</image>
						</view>
					</view>
					<view class="reserved-information-box">
						<view class="yuliu-text">预留信息</view>
						<view class="flex-between-content"
							@click="link(`/page_my/reserved/index?id=${list[0].storeId}`)">
							<view class="information-box" v-if="userInfo.name && userInfo.phone">
								<view class="name"> {{ userInfo.name }}</view>
								<view class="phone">{{ userInfo.phone }}</view>
							</view>
							<view v-else class="information-box"> 请选择 </view>
							<image class="go-change" :src="`${img_baseUrl}/statics/std/static/go_gray.png`">
							</image>
						</view>
					</view>
					<view class='bor_bot'></view>
					<view class="contact-business-box" v-if="pickUpInfo.centersPhone">
						<image class="icon-phone" :src="`${img_baseUrl}/statics/std/static/icon-phone.png`">
						</image>
						<view class="contact-business0-txt" @click="makePhoneCall">
							联系商家
						</view>
					</view>
				</view>
				
			</view>

			<view class="shop-info" v-for="store in list" :key="store.storeId">
				<view class="shop-left">
					<image class="shop-avatar" :src="`${img_baseUrl}/statics/std/static/new/shop_green.png`" />
					<text class="shop-title">{{ store.storeName }}</text>
				</view>
				<view class="info-box" v-for="goods in store.goods" :key="goods.id">
					<view class="left">
						<image class="avatar" :src="img_baseUrl + goods.imgAbbrev" />
					</view>
					<view class="right">
						<view class="title">{{ goods.name }}</view>
						<view class="shop-desc" v-if="goods.goodsSpec">
							<text class="shop-desc_item">{{ goods.goodsSpec }}</text>
						</view>
						<view class="price-num-box">
							<view class="price">¥{{ goods.toShowPrice }}</view>
							<view class="num">x {{ goods.goodsNum }}</view>
						</view>
					</view>
				</view>
        <view class="freight-box" v-if="tabActive === 1">
        	<view class="freight-label">运费</view>
        	<view class="freight-text" v-if="addressInfo.id">¥{{ freight }}</view>
        	<view class="freight-text" v-else>--</view>
        </view>
			</view>
		</view>
		<view class="btn-box">
			<view class="count-price-box">
				<view class="count-label">已选{{ goodsCountNum }}件</view>
				<view>
					<text>总计</text>
					<text
						class="count-value">¥{{ tabActive === 1 ? (parseFloat(goodsCountPrice) + parseFloat(freight)).toFixed(2) : goodsCountPrice }}</text>
				</view>
			</view>
			<button class="go-pay" :loading="isSubmitting" :disabled="isSubmitting" @click="placeOrder">提交订单</button>
		</view>
	</view>
</template>

<script>
	import requestPost, {
		requestGet
	} from "../../utils/request";
	import {
		Decimal
	} from "decimal.js";
	import {
		throttle
	} from '@/utils/index.js'

	const img_api = process.env.VUE_APP_BASEURL_IMG_API;
	export default {
		data() {
			return {
				pageLoaded: false,
				loading: 2, // 0:不再加载; 1:加载中; 2:加载完成;
				img_baseUrl: img_api,
				tabActive: 1,
				addressInfo: {},
				freight: 0,
				storeInfo: {},
				pickUpInfo: {},
				userInfo: {
					userId: null,
					phone: "",
					name: "",
				},
				isSubmitting: false,
				addSelId: null
			};
		},
		computed: {
			sourceList() {
				return this.$store.state.settlementGoods;
			},
			list() {
				return this.formatData(this.$store.state.settlementGoods);
			},
			goodsCountNum() {
				return this.list.reduce((acc, store) => {
					return acc + store.goods.length;
				}, 0);
			},
			goodsCountPrice() {
				return this.list
						.reduce((acc, store) => {
							return store.goods.reduce((_acc, goods) => {
								return new Decimal(_acc)
									.add(new Decimal(goods.price).mul(new Decimal(goods.goodsNum)))
									.toNumber();
							}, acc);
						}, 0)
					.toFixed(2);
			},
			addressDetail() {
				return this.tabActive === 1 ?
					this.addressInfo.provinceName +
					this.addressInfo.cityName +
					this.addressInfo.countyName :
					this.pickUpInfo.provinceName +
					this.pickUpInfo.cityName +
					this.pickUpInfo.countyName;
			},
			addressDetailInfo() {
				return this.tabActive === 1 ?
					this.addressInfo.address :
					this.pickUpInfo.address;
			},
			deliveryName() {
				return this.tabActive === 1 ? this.addressInfo.name : this.userInfo.name;
			},
			deliveryPhone() {
				return this.tabActive === 1 ?
					this.addressInfo.phone :
					this.userInfo.phone;
			},
      deliveryInfo() {
        if (this.tabActive === 1) {
          return this.addressInfo;
        }
        if (this.tabActive === 2) {
          return {
            ...this.pickUpInfo,
            ...this.userInfo,
          };
        }
      },
		},
		onLoad() {
			this.getInfo();
		},
		onShow() {
			const userInfo = uni.getStorageSync("X-UserInfo");
			this.userInfo.userId =
				this.$store.state.selectPickUpInfo.userId || userInfo.userId;
			this.userInfo.name =
				this.$store.state.selectPickUpInfo.name || userInfo.nickName;
			this.userInfo.phone =
				this.$store.state.selectPickUpInfo.phone || userInfo.phonenumber;
			console.log('变化了地址', this.$store.state.selectAddress)
			this.getAddressList();
			this.getPickUpList();
		},
		methods: {
			placeOrder: throttle(function() {
				if (!this.addressDetail || !this.addressDetailInfo) {
					if (this.tabActive === 1) {
						uni.showToast({
							title: "请选择收货地址",
							icon: "none",
						});
					}
					if (this.tabActive === 2) {
						uni.showToast({
							title: "请选择自提点",
							icon: "none",
						});
					}
					return
				}
				if (!this.deliveryName) {
					uni.showToast({
						title: "请输入收货人姓名",
						icon: "none",
					});
					return
				}
				if (!this.deliveryPhone) {
					uni.showToast({
						title: "请输入收货人手机号",
						icon: "none",
					});
					return
				}
				let param = {
					cartIds: [],
					postagePrice: this.tabActive === 1 ? Number(this.freight) : 0, // 运费
					storeId: this.list[0].storeId,
					orderAddressId: this.deliveryInfo.id,
					addressProvince: this.deliveryInfo.provinceName, // 省份
					addressCity: this.deliveryInfo.cityName, // 城市
					addressCityCode: this.deliveryInfo.city, // 城市编码
					addressCounty: this.deliveryInfo.countyName, // 区县
					addressDetail: this.deliveryInfo.address, // 详细地址
					deliveryMethod: this.tabActive, // 是否自提
					deliveryName: this.deliveryInfo.name, // 收货人姓名
					deliveryPhone: this.deliveryInfo.phone, // 收货人手机
					shopOrderDetailsAddDTOList: [],
				};
				for (const goods of this.sourceList) {
					if (goods.id) {
						param.cartIds.push(goods.id);
					}
					param.shopOrderDetailsAddDTOList.push({
            goodPic: goods.imgAbbrev, // 商品缩略图
            goodsCount: goods.goodsNum, // 数量
            goodsId: goods.goodsId, // 商品id
            goodsName: goods.name, // 商品名称
            goodsSpec: goods.goodsSpec, // 商品规格
            postagePrice: this.tabActive === 1 ? Number(this.freight) : 0, // 运费
            ...(goods.skuId ? { skuId: goods.skuId } : {}),
            storeId: goods.storeId, // 商店id
            storeName: goods.storeName, // 商店名称
            unitPrice: goods.price, // 商品单价
					});
				}
				console.log("下单参数：", param)
				this.isSubmitting = true;
				return requestPost("/order/mobile/shop", param).then(
					({
						code,
						data,
						msg
					}) => {
						this.isSubmitting = false;
						if (code === 200) {
              const total = this.tabActive === 1 ? (parseFloat(this.goodsCountPrice) + parseFloat(this.freight)).toFixed(2) : this.goodsCountPrice;
							if (total == 0.00) {
								uni.redirectTo({
									url: `/page_mall/result/index?state=1&id=${data}`,
								});
								return
							}
							this.getPayOrderInfo(data);
						} else {
							uni.showToast({
								icon: "none",
								title: msg,
                duration: 3000
							})
						}
					}
				);
			}, 500),
			formatData(list) {
				const grouped = list.reduce((acc, item) => {
					if (!acc[item.storeId]) {
						acc[item.storeId] = {
							storeId: item.storeId,
							storeName: item.storeName,
							goods: [],
						};
					}
					acc[item.storeId].goods.push({
						...item,
						toShowPrice: item.price.toFixed(2)
					});
					return acc;
				}, []);

				return Object.values(grouped);
			},
			getFreight() {
				if (
					!this.addressInfo.city &&
					!this.addressInfo.county &&
					!this.addressInfo.province
				) {
					return Promise.reject({
						msg: "需要选地址才能查询到邮费",
					});
				}
        console.log("freight====", this.addressInfo, this.list);

        let params = [];
        this.list.map(i => {
          i.goods.map(g => {
            if(g.skuId){
              params.push({ "skuId": g.skuId, "goodsId": g.goodsId, "cityCode": this.addressInfo.city, "num": g.goodsNum })
            }else{
              params.push({ "goodsId": g.goodsId, "cityCode": this.addressInfo.city, "num": g.goodsNum })
            }
          })
        })
				return requestPost("/shop/mobile/goods/calculateFreights", params).then(({
					code,
					data
				}) => {
					if (code === 200) {
						this.freight = data?.totalFreights.toFixed(2) || "0.00";
					} else {
						this.freight = "0.00";
					}
				});
			},
			changeTab(index) {
				this.tabActive = index;
			},
			link(url) {
				uni.navigateTo({
					url,
				});
			},
			// 支付前获取订单详细
			getPayOrderInfo(orderId) {
				return requestGet(`/pay/pay/transactions/shop/${orderId}`).then((res) => {
					if (res.code === 200) {
						console.log('获取了支付的数据', res)
						//调用微信官方支付接口弹出付款界面,输入密码扣款
						wx.requestPayment({
							provider: "wxpay",
							timeStamp: String(res.data.timeStamp),
							nonceStr: res.data.nonceStr,
							package: res.data.package,
							signType: res.data.signType,
							paySign: res.data.paySign,
							success(res) {
								console.log("success:" + JSON.stringify(res));
								uni.redirectTo({
									url: `/page_mall/result/index?state=1&id=${orderId}`,
								});
							},
							fail(err) {
								console.log("fail:" + JSON.stringify(err));
								uni.redirectTo({
									url: `/page_mall/result/index?state=0&id=${orderId}`,
								});
							},
						});
					}
				});
			},
			getInfo() {
				return requestGet(`/shop/mobile/store/${this.sourceList[0].storeId}`)
					.then((res) => {
						this.storeInfo = res.data;
					})
					.catch((err) => console.log("错误了", err));
			},
			getAddressList() {
				return requestGet("/shop/mobile/receiveAddress/listBySelf", {
						pageNum: 1,
						pageSize: 100,
					})
					.then((res) => {
						if (res.code === 200) {
							if (res.rows.length > 0) {
								res.rows.forEach((item) => {
									if (this.$store.state.selectAddress.id) {
										if ((item.id == this.$store.state.selectAddress.id)) {
											this.addressInfo = item;
											this.addSelId = item.id
										}
									} else {
										if (item.isDefault == 1) {
											this.addressInfo = item;
										}
									}
								});
							}
						}
						console.log("111111111===", this.addressInfo);
						this.getFreight();
					})
					.catch((err) => console.log("错误了", err));
			},
			getPickUpList() {
				return requestGet(`/shop/mobile/store/centers/${this.list[0].storeId}`)
					.then((res) => {
						if (res.code === 200) {
							res.data.forEach((item) => {
								if (this.$store.state.selectPickUpPoint.id) {
									if (this.$store.state.selectPickUpPoint.id == item.id) {
										this.pickUpInfo = item;
									}
								} else {
									this.pickUpInfo = res.data.length > 0 ? res.data[0] : {};
								}
							});
						}
					})
					.catch((err) => console.log("错误了", err));
			},
			makePhoneCall() {
				uni.makePhoneCall({
					phoneNumber: this.pickUpInfo.centersPhone, //仅为示例
				});
			},
		},
	};
</script>

<style lang="scss">
	page {
		background: #f7f9fa;
	}

	.settle-box {
		margin: 22rpx 32rpx 0;
		padding-bottom: calc(22rpx + 124rpx + env(safe-area-inset-bottom));
	}

	.settle-type-box {
		margin-bottom: -8rpx;
		
		

		.tabs {
			display: flex;
			align-items: center;
			height: 64rpx;
			background: rgba(63,170,115,0.1);
			border-radius: 24rpx 24rpx 0rpx 0rpx;
		}

		.tab {
			width: 50%;
			text-align: center;
			font-size: 28rpx;
			font-weight: 400;
			color: #5f6f86;
			line-height: 64rpx;

			&.active {
				height: 76rpx;
				background: url("../../static/tab-active-left.png") no-repeat;
				background-size: 100% 100%;
				line-height: 76rpx;
			}

			&.active1 {
				height: 76rpx;
				background: url("../../static/tab-active-right.png") no-repeat;
				background-size: 100% 100%;
				line-height: 76rpx;
			}
		}

		.mail {
			padding: 32rpx 24rpx;
			background: #ffffff;
			border-radius: 0rpx 0rpx 24rpx 24rpx;
			position: relative;
			
			.bor_bot {
				width: 100%;
				height: 8rpx;
				position: absolute;
				left: 0;
				bottom: 0;
				background-image: url('../../static/new/bor_bot.png');
				background-repeat: no-repeat;
				background-size: 100% 100%;
				border-radius: 0 0 24rpx 24rpx;
			}
			.address {
				font-size: 24rpx;
				font-weight: 400;
				color: rgba(0, 0, 0, 0.7);
				line-height: 32rpx;
				padding-bottom: 24rpx;
			}

			.isDefault {
				margin-left: 26rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #3FAA73;
				line-height: 32rpx;
				padding: 0 8rpx;
				background: rgba(63,170,115,0.1);
				border-radius: 8rpx 8rpx 8rpx 8rpx;
			}

			.is-pic-up {
				margin-right: 20rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #2187ff;
				line-height: 32rpx;
				padding: 0 8rpx;
				background: rgba(77, 134, 247, 0.102);
				border-radius: 8rpx 8rpx 8rpx 8rpx;
			}

			.address-desc {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 32rpx;
				font-weight: 500;
				color: rgba(0, 0, 0, 0.8);
				line-height: 44rpx;
				padding-bottom: 24rpx;

				.address-txt {
					font-size: 32rpx;
					font-weight: 700;
					color: rgba(0, 0, 0, 0.8);
					line-height: 44rpx;
				}
			}

			.no-address-box {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.left-box {
					display: flex;
					align-items: center;
				}

				.add-icon {
					display: block;
					width: 48rpx;
					height: 48rpx;
					margin-right: 8rpx;
				}

				.add-txt {
					font-size: 32rpx;
					font-weight: 700;
					color: rgba(0, 0, 0, 0.8);
					line-height: 44rpx;
				}
			}
		}

		.go-change {
			display: block;
			width: 32rpx;
			height: 32rpx;
		}

		.name {
			font-size: 28rpx;
			font-weight: 400;
			color: rgba(0, 0, 0, 0.7);
			line-height: 40rpx;
			padding-right: 24rpx;
		}

		.phone {
			font-size: 28rpx;
			font-weight: 400;
			color: rgba(0, 0, 0, 0.7);
		}

		.flex-between-content {
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex: 1;
		}

		.pick-up {
			padding: 32rpx 24rpx;
			background: #ffffff;
			border-radius: 0rpx 0rpx 24rpx 24rpx;
			position: relative;
			
			.bor_bot {
				width: 100%;
				height: 8rpx;
				position: absolute;
				left: 0;
				bottom: 92rpx;
				background-image: url('../../static/new/bor_bot.png');
				background-repeat: no-repeat;
				background-size: 100% 100%;
			}

			.pick-up-text {
				font-size: 28rpx;
				font-weight: 400;
				color: rgba(0, 0, 0, 0.5);
				line-height: 40rpx;
				padding-right: 52rpx;
			}

			.adress-text {
				width: 442rpx;
				height: 80rpx;
				font-size: 28rpx;
				font-weight: 700;
				color: rgba(0, 0, 0, 0.8);
				line-height: 40rpx;
				padding-right: 28rpx;
				word-break: break-all;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				/* 这里是超出几行省略 */
				overflow: hidden;
			}

			.address-desc {
				display: flex;
				align-items: self-start;
				font-size: 32rpx;
				font-weight: 500;
				color: rgba(0, 0, 0, 0.8);
				line-height: 44rpx;
				padding-bottom: 24rpx;
			}

			.reserved-information-box {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.yuliu-text {
					font-size: 28rpx;
					font-weight: 400;
					color: rgba(0, 0, 0, 0.5);
					line-height: 32rpx;
					padding-right: 24rpx;
				}

				.information-box {
					display: flex;
					align-items: center;
				}

				.name {
					font-size: 28rpx;
					font-weight: 700;
					color: rgba(0, 0, 0, 0.8);
					line-height: 40rpx;
				}

				.phone {
					font-size: 28rpx;
					font-weight: 700;
					color: rgba(0, 0, 0, 0.8);
					line-height: 40rpx;
				}

				.go-change {
					width: 32rpx;
					height: 32rpx;
					display: block;
				}
			}

			.contact-business-box {
				padding-top: 24rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-top: 1rpx solid rgba(0, 0, 0, 0.1);
				margin-top: 24rpx;

				.icon-phone {
					width: 40rpx;
					height: 40rpx;
					margin-right: 16rpx;
				}

				.contact-business0-txt {
					font-size: 28rpx;
					font-weight: 400;
					color: rgba(0, 0, 0, 0.8);
					line-height: 40rpx;
				}
			}
		}
	}

	.shop-info {
		margin-top: 24rpx;
		background: #ffffff;
		border-radius: 24rpx;
		padding: 24rpx;

		.shop-left {
			display: flex;
			margin-bottom: 32rpx;
			padding: 4rpx 0;
		}

		.shop-avatar {
			width: 40rpx;
			height: 40rpx;
			margin-right: 16rpx;
		}

		.shop-title {
			font-size: 28rpx;
			font-weight: 400;
			color: #777f8f;
			line-height: 40rpx;
		}

		.info-box {
			display: flex;
			align-items: center;
      flex-direction: row;
      flex-wrap: wrap;
			margin-bottom: 24rpx;
		}

		.left {
			flex: none;
			width: 160rpx;
			height: 160rpx;
			margin-right: 24rpx;

			.avatar {
				width: 100%;
				height: 100%;
				border-radius: 16rpx;
			}
		}

		.right {
			flex: auto;
			height: 160rpx;
			display: flex;
			flex-flow: column nowrap;

			.title {
				font-size: 32rpx;
				font-weight: 400;
				color: rgba(0, 0, 0, 0.8);
				line-height: 44rpx;
			}

			.shop-desc {
				font-size: 24rpx;
				font-weight: 400;
				color: #5f6f86;
				line-height: 32rpx;
				margin-top: 16rpx;

				.shop-desc_item {
					background: #f7f9fa;
					box-sizing: border-box;
					padding: 4rpx 8rpx;
					border-radius: 8rpx;
				}
			}

			.price-num-box {
				height: 44rpx;
				margin-top: auto;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.price {
				font-size: 32rpx;
				font-weight: 700;
				color: rgba(0, 0, 0, 0.8);
				line-height: 34rpx;
				padding-top: 2rpx;
			}

			.num {
				font-size: 32rpx;
				font-weight: 400;
				color: rgba(0, 0, 0, 0.7);
				line-height: 44rpx;
			}
		}

		.freight-box {
      width: 100%;
			margin-top: 32rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.freight-label {
				font-size: 28rpx;
				font-weight: 400;
				color: #777f8f;
				line-height: 48rpx;
			}

			.freight-text {
				font-size: 28rpx;
				font-weight: 700;
				color: rgba(0, 0, 0, 0.8);
				line-height: 48rpx;
			}
		}
	}

	.btn-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		bottom: 0;
		width: calc(100% - 64rpx);
		height: 120rpx;
		padding-left: 32rpx;
		padding-right: 32rpx;
		background: #ffffff;
		border: 2rpx solid rgba(0, 0, 0, 0.1);
		padding-bottom: calc(4rpx + env(safe-area-inset-bottom));

		.count-price-box {
			font-size: 24rpx;
			font-weight: 400;
			color: rgba(0, 0, 0, 0.7);
			line-height: 34rpx;
			display: flex;
			flex-flow: column nowrap;

			.count-label {
				color: rgba(0, 0, 0, 0.5);
				margin-bottom: 10rpx;
			}

			.count-value {
				font-size: 36rpx;
				font-weight: 700;
				color: #ff7614;
				line-height: 44rpx;
				margin-left: 16rpx;
			}
		}

		.go-pay {
			width: 240rpx;
			height: 88rpx;
			margin: 0;
			margin-left: 32rpx;
			background: #3FAA73;
			border-radius: 44rpx 44rpx 44rpx 44rpx;
			font-size: 32rpx;
			font-weight: 500;
			color: #ffffff;
			line-height: 88rpx;
			text-align: center;
		}
	}
</style>